const groupService = require('../services/groupService');
const { notifyGroupJoinRequest } = require('../services/socketService');

// @desc    创建群组
// @route   POST /api/groups
// @access  Private
const createGroup = async (req, res) => {
  try {
    const { name, description, group_avatar } = req.body;
    
    if (!name) {
      return res.status(400).json({ message: '群组名称不能为空' });
    }
    
    const group = await groupService.createGroup(
      req.user._id.toString(),
      name,
      description,
      group_avatar
    );
    
    res.status(201).json(group);
  } catch (error) {
    console.error('创建群组失败:', error);
    res.status(500).json({ message: error.message || '创建群组失败' });
  }
};

// @desc    获取用户加入的群组列表
// @route   GET /api/groups
// @access  Private
const getUserGroups = async (req, res) => {
  try {
    const groups = await groupService.getUserGroups(req.user._id.toString());
    res.json(groups);
  } catch (error) {
    console.error('获取用户群组失败:', error);
    res.status(500).json({ message: error.message || '获取用户群组失败' });
  }
};

// @desc    获取群组详情
// @route   GET /api/groups/:groupId
// @access  Private
const getGroupById = async (req, res) => {
  try {
    const { groupId } = req.params;
    const group = await groupService.getGroupInfo(groupId, req.user._id.toString());
    res.json(group);
  } catch (error) {
    console.error('获取群组详情失败:', error);
    
    if (error.message === '群组不存在' || error.message === '您不是该群组的成员') {
      return res.status(404).json({ message: error.message });
    }
    
    res.status(500).json({ message: error.message || '获取群组详情失败' });
  }
};

// @desc    通过邀请码查找群组
// @route   GET /api/groups/code/:groupCode
// @access  Private
const findGroupByCode = async (req, res) => {
  try {
    const { groupCode } = req.params;
    const group = await groupService.findGroupByCode(groupCode);
    
    if (!group) {
      return res.status(404).json({ message: '找不到该群组' });
    }
    
    res.json(group);
  } catch (error) {
    console.error('查找群组失败:', error);
    res.status(500).json({ message: error.message || '查找群组失败' });
  }
};

// @desc    邀请用户加入群组
// @route   POST /api/groups/:groupId/invite
// @access  Private
const inviteToGroup = async (req, res) => {
  try {
    const { groupId } = req.params;
    const { userId } = req.body;
    
    if (!userId) {
      return res.status(400).json({ message: '用户ID不能为空' });
    }
    
    const result = await groupService.inviteToGroup(
      groupId,
      req.user._id.toString(),
      userId
    );
    
    res.json(result);
  } catch (error) {
    console.error('邀请用户加入群组失败:', error);
    
    if (error.message.includes('不是该群组的成员') || 
        error.message.includes('已经是群组成员') ||
        error.message.includes('已经向该用户发送过邀请')) {
      return res.status(400).json({ message: error.message });
    }
    
    res.status(500).json({ message: error.message || '邀请用户加入群组失败' });
  }
};

// @desc    获取待处理的群组邀请
// @route   GET /api/groups/invitations
// @access  Private
const getPendingGroupInvitations = async (req, res) => {
  try {
    const invitations = await groupService.getPendingGroupInvitations(req.user._id.toString());
    res.json(invitations);
  } catch (error) {
    console.error('获取群组邀请失败:', error);
    res.status(500).json({ message: error.message || '获取群组邀请失败' });
  }
};

// @desc    响应群组邀请
// @route   PUT /api/groups/invitations/:invitationId
// @access  Private
const respondToGroupInvitation = async (req, res) => {
  try {
    const { invitationId } = req.params;
    const { action } = req.body;
    
    if (!action || !['accepted', 'rejected'].includes(action)) {
      return res.status(400).json({ message: '无效的操作' });
    }
    
    const result = await groupService.respondToGroupInvitation(
      invitationId,
      req.user._id.toString(),
      action
    );
    
    res.json(result);
  } catch (error) {
    console.error('响应群组邀请失败:', error);
    
    if (error.message === '邀请不存在或已处理') {
      return res.status(404).json({ message: error.message });
    }
    
    res.status(500).json({ message: error.message || '响应群组邀请失败' });
  }
};

// @desc    申请加入群组
// @route   POST /api/groups/:groupId/join
// @access  Private
const requestJoinGroup = async (req, res) => {
  try {
    console.log(`📝 收到群组加入请求: 用户 ${req.user._id} 申请加入群组 ${req.params.groupId}`);
    
    const { groupId } = req.params;
    const userId = req.user._id.toString();
    
    // 获取Socket.IO实例
    const io = req.app.get('socketio');
    
    try {
      const result = await groupService.requestJoinGroup(groupId, userId);
      
      console.log('✅ 申请加入群组成功，发送通知给群管理员');
      
      // 发送Socket.IO通知给群管理员
      if (io) {
        const notifyResult = await notifyGroupJoinRequest(groupId, userId, io);
        console.log(`📤 通知发送结果: ${notifyResult ? '成功' : '失败'}`);
      } else {
        console.log('❌ Socket.IO实例未找到，无法发送通知');
      }
      
      res.json(result);
    } catch (serviceError) {
      // 如果是重复请求，仍然尝试发送通知给管理员
      if (serviceError.message.includes('已经发送过加入请求')) {
        console.log('⚠️ 用户已发送过加入请求，但仍发送通知提醒群主');
        
        if (io) {
          const notifyResult = await notifyGroupJoinRequest(groupId, userId, io);
          console.log(`📤 重复请求通知发送结果: ${notifyResult ? '成功' : '失败'}`);
        }
      }
      
      // 抛出原始错误
      throw serviceError;
    }
  } catch (error) {
    console.error('申请加入群组失败:', error);
    
    if (error.message.includes('不存在') || 
        error.message.includes('已经是该群组的成员') || 
        error.message.includes('已经发送过加入请求')) {
      return res.status(400).json({ message: error.message });
    }
    
    res.status(500).json({ message: error.message || '申请加入群组失败' });
  }
};

// @desc    获取群组的待处理加入请求
// @route   GET /api/groups/:groupId/join-requests
// @access  Private
const getPendingJoinRequests = async (req, res) => {
  try {
    const { groupId } = req.params;
    const requests = await groupService.getPendingJoinRequests(groupId, req.user._id.toString());
    res.json(requests);
  } catch (error) {
    console.error('获取加入请求失败:', error);
    
    if (error.message === '您不是该群组的管理员') {
      return res.status(403).json({ message: error.message });
    }
    
    res.status(500).json({ message: error.message || '获取加入请求失败' });
  }
};

// @desc    响应加入群组请求
// @route   PUT /api/groups/:groupId/join-requests/:requestId
// @access  Private
const respondToJoinRequest = async (req, res) => {
  try {
    const { requestId } = req.params;
    const { action } = req.body;
    
    if (!action || !['accepted', 'rejected'].includes(action)) {
      return res.status(400).json({ message: '无效的操作' });
    }
    
    const result = await groupService.respondToJoinRequest(
      requestId,
      req.user._id.toString(),
      action
    );
    
    res.json(result);
  } catch (error) {
    console.error('响应加入请求失败:', error);
    
    if (error.message === '请求不存在或已处理') {
      return res.status(404).json({ message: error.message });
    }
    
    if (error.message === '您不是该群组的管理员') {
      return res.status(403).json({ message: error.message });
    }
    
    res.status(500).json({ message: error.message || '响应加入请求失败' });
  }
};

// @desc    离开群组
// @route   POST /api/groups/:groupId/leave
// @access  Private
const leaveGroup = async (req, res) => {
  try {
    const { groupId } = req.params;
    const result = await groupService.leaveGroup(groupId, req.user._id.toString());
    res.json(result);
  } catch (error) {
    console.error('离开群组失败:', error);
    
    if (error.message === '您不是该群组的成员') {
      return res.status(400).json({ message: error.message });
    }
    
    res.status(500).json({ message: error.message || '离开群组失败' });
  }
};

// @desc    更新群组信息
// @route   PUT /api/groups/:groupId
// @access  Private
const updateGroupInfo = async (req, res) => {
  try {
    const { groupId } = req.params;
    const { name, description, group_avatar } = req.body;
    
    const updatedGroup = await groupService.updateGroupInfo(
      groupId,
      req.user._id.toString(),
      { name, description, group_avatar }
    );
    
    res.json(updatedGroup);
  } catch (error) {
    console.error('更新群组信息失败:', error);
    
    if (error.message === '您不是该群组的管理员') {
      return res.status(403).json({ message: error.message });
    }
    
    if (error.message === '没有提供要更新的数据') {
      return res.status(400).json({ message: error.message });
    }
    
    res.status(500).json({ message: error.message || '更新群组信息失败' });
  }
};

// @desc    管理群组成员（移除成员或更新角色）
// @route   PUT /api/groups/:groupId/members/:userId
// @access  Private
const manageGroupMember = async (req, res) => {
  try {
    const { groupId, userId } = req.params;
    const { action, role } = req.body;
    
    if (!action || !['remove', 'updateRole'].includes(action)) {
      return res.status(400).json({ message: '无效的操作' });
    }
    
    if (action === 'updateRole' && (!role || !['member', 'admin'].includes(role))) {
      return res.status(400).json({ message: '无效的角色' });
    }
    
    const result = await groupService.manageGroupMember(
      groupId,
      req.user._id.toString(),
      userId,
      action,
      role
    );
    
    res.json(result);
  } catch (error) {
    console.error('管理群组成员失败:', error);
    
    if (error.message === '您不是该群组的管理员') {
      return res.status(403).json({ message: error.message });
    }
    
    if (error.message.includes('无法对群组创建者执行此操作') || 
        error.message.includes('目标用户不是该群组的成员')) {
      return res.status(400).json({ message: error.message });
    }
    
    res.status(500).json({ message: error.message || '管理群组成员失败' });
  }
};

// @desc    删除群组
// @route   DELETE /api/groups/:groupId
// @access  Private
const deleteGroup = async (req, res) => {
  try {
    const { groupId } = req.params;
    const result = await groupService.deleteGroup(groupId, req.user._id.toString());
    res.json(result);
  } catch (error) {
    console.error('删除群组失败:', error);
    
    if (error.message === '群组不存在') {
      return res.status(404).json({ message: error.message });
    }
    
    if (error.message === '只有群组创建者才能删除群组') {
      return res.status(403).json({ message: error.message });
    }
    
    res.status(500).json({ message: error.message || '删除群组失败' });
  }
};

// @desc    获取用户在群组中的权限
// @route   GET /api/groups/:groupId/permissions
// @access  Private
const getUserGroupPermissions = async (req, res) => {
  try {
    const { groupId } = req.params;
    const permissions = await groupService.getUserGroupPermissions(groupId, req.user._id.toString());
    res.json(permissions);
  } catch (error) {
    console.error('获取用户群组权限失败:', error);
    
    if (error.message === '群组不存在') {
      return res.status(404).json({ message: error.message });
    }
    
    res.status(500).json({ message: error.message || '获取用户群组权限失败' });
  }
};

module.exports = {
  createGroup,
  getUserGroups,
  getGroupById,
  findGroupByCode,
  inviteToGroup,
  getPendingGroupInvitations,
  respondToGroupInvitation,
  requestJoinGroup,
  getPendingJoinRequests,
  respondToJoinRequest,
  leaveGroup,
  updateGroupInfo,
  manageGroupMember,
  deleteGroup,
  getUserGroupPermissions
}; 